package net.wanderinghorse.jsonmessage.response;

import net.wanderinghorse.json.JSONArray;
import net.wanderinghorse.json.JSONUtil;
import net.wanderinghorse.jsonmessage.JSONMessage;
import net.wanderinghorse.jsonmessage.Response;
import net.wanderinghorse.jsonmessage.Request;
import net.wanderinghorse.jsonmessage.AbstractRequestHandler;
import net.wanderinghorse.json.JSONObject;

/**
 * Implements the ChuckNorris message response, as described in the library
 * manual.
 */
public class ChuckNorris extends AbstractRequestHandler {

    private static JSONArray db;

    /**
     * Reads the internal configuration.
     * @return True if the db can be loaded, else false.
     */
    private boolean readDb()
    {
//        synchronized ( ChuckNorris.class ) {
//            if( null != db ) return true;
//            JSONObject jo = JSONMessage.getConfig();
//            if( null == jo ) return false;
//            jo = jo.optJSONObject("ChuckNorris");
//            if( null == jo ) return false;
//            db = jo.optJSONArray( "db" );
//            return ( null != db );
//        }
        if( null != db ) return true;
        synchronized ( ChuckNorris.class ) {
            if( null != db ) return true;
            JSONObject jo = JSONUtil.getConfigObject(getClass());
            if( null == jo ) return false;
            db = jo.optJSONArray("db");
        }
        return ( null != db );
    }

    /**
     * Overridden to add ChuckNorris-specific data to the response.
     *
     * As an addition to the response structure defined in the library manual,
     * if the request payload is an object and contains the key "all" with
     * the value true then the response payload structure looks like this:
     *
     * {"all":[ ... list of Chuck Norris quotes (strings) ...]}
     *
     * @param req The request object which caused the fetching of the response.
     * @param resp The response object to populate.
     */
    protected void doProcessResponse(final Request req, final Response resp) throws Exception {
        if( ! readDb() ) {
            resp.setResultCode(1);
            resp.setResultText("Could not load Chuck Norris trivia from configuration data!");
            return;
        }
        JSONObject popt = this.getPayloadObject( req );
        boolean doAll = false;
        if( null != popt ) {
            doAll = popt.optBoolean( "all", false );
        }
        JSONObject pay = new JSONObject();
        int count = db.length();
        int pos = (int)(Math.random() * (count*100) % count);
        if( doAll ) {
            pay.put( "all", db );
        }
        else {
            pay.put("number", pos );
            pay.put( "of", count );
            pay.put( "quote", db.get(pos) );
        }
        resp.setPayload( pay );
    }
}
